package tech.spiro.test.logger.logback;

import ch.qos.logback.core.rolling.RolloverFailure;
import ch.qos.logback.core.rolling.helper.CompressionMode;
import ch.qos.logback.core.rolling.helper.Compressor;

import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class DelayCompressor extends Compressor {

    private final int delayInSeconds;

    public DelayCompressor(CompressionMode compressionMode, int delayInSeconds) {
        super(compressionMode);
        this.delayInSeconds = delayInSeconds;
    }

    @Override
    public Future<?> asyncCompress(String nameOfFile2Compress, String nameOfCompressedFile, String innerEntryName) throws RolloverFailure {
        CompressionRunnable runnable = new CompressionRunnable(nameOfFile2Compress, nameOfCompressedFile, innerEntryName);
        ScheduledExecutorService executorService = context.getScheduledExecutorService();
        return executorService.schedule(runnable, delayInSeconds, TimeUnit.SECONDS);
    }

    class CompressionRunnable implements Runnable {
        final String nameOfFile2Compress;
        final String nameOfCompressedFile;
        final String innerEntryName;

        public CompressionRunnable(String nameOfFile2Compress, String nameOfCompressedFile, String innerEntryName) {
            this.nameOfFile2Compress = nameOfFile2Compress;
            this.nameOfCompressedFile = nameOfCompressedFile;
            this.innerEntryName = innerEntryName;
        }

        public void run() {
            DelayCompressor.this.compress(nameOfFile2Compress, nameOfCompressedFile, innerEntryName);
        }
    }

    public int getDelayInSeconds() {
        return delayInSeconds;
    }

}
